package com.wm.task.server.dao;

import com.wm.task.common.util.FileHelper;
import com.wm.task.common.util.IDCreator;
import com.wm.task.common.vo.Student;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Student进行持久化到文件的操作对象  服务器端
 */
public class StudentDAO {
    private static final String DATA_PATH = "student/";
    private static StudentDAO instance;

    private StudentDAO() {
    }

    public static StudentDAO getInstance() {
        if (instance == null) {
            instance = new StudentDAO();
        }
        return instance;
    }

    public List<Student> findAll() {
        List<Student> students = new ArrayList<>();
        //如何读取目录中的文件，每个文件变为一个对象
        File dir = FileHelper.getFile(DATA_PATH);
        File[] files = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                try {
                    Student student = (Student) FileHelper.readObjectFile(file);
                    if (student != null) {
                        students.add(student);
                    }
                } catch (Exception e) {
                }
            }
        }
        return students;
    }

    public void save(Student student) {
        if (student.getId() == null) {
            student.setId(IDCreator.getId());
        }
        File file = FileHelper.getFile(DATA_PATH + student.getName() + ".stu");
        FileHelper.writeObjectFile(file, student);
    }

    public boolean delete(Student student) {
       return FileHelper.getFile(DATA_PATH + student.getName() + ".stu").delete();

    }
}
